package com.hc.testaudio.deletea.ui

import android.annotation.SuppressLint
import android.media.MediaPlayer
import android.media.audiofx.Equalizer
import android.media.audiofx.Visualizer
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import com.hc.testaudio.deletea.util.VisualizerView
import android.media.audiofx.Visualizer.OnDataCaptureListener
import android.widget.SeekBar.OnSeekBarChangeListener
import android.media.MediaPlayer.OnCompletionListener
import android.media.AudioManager
import com.hc.testaudio.R


/**
 *
 */
class AudioChartActivity : BaseActivity() {

    private final val VISUALIZER_HEIGHT_DIP = 50f

    private var mMediaPlayer: MediaPlayer? = null
    private lateinit var mVisualizer: Visualizer
    private lateinit var mEqualizer: Equalizer // 均衡器

    private lateinit var mLayout: LinearLayout
    lateinit var mVisualizerView: VisualizerView
    private lateinit var mStatusTextView: TextView
    override fun getLayoutId(): Int {
        return R.layout.audio_chart_activity
    }

    override fun initView(savedInstanceState: Bundle?) {
        volumeControlStream = AudioManager.STREAM_MUSIC

        mStatusTextView = TextView(this)
        mLayout = LinearLayout(this)
        mLayout.setOrientation(LinearLayout.VERTICAL)
        mLayout.addView(mStatusTextView)
        setContentView(mLayout)

        mMediaPlayer = MediaPlayer.create(this, R.raw.hz1000)

        setupVisualizerFxAndUi()
        setupEqualizeFxAndUi()

        mVisualizer.setEnabled(true)
        mMediaPlayer!!.setOnCompletionListener(OnCompletionListener {
            mVisualizer.setEnabled(false)
        })

        mMediaPlayer!!.start()
        mStatusTextView.setText("播放中。。。")
    }


    /**
     * 通过mMediaPlayer返回的AudioSessionId创建一个优先级为0均衡器对象 并且通过频谱生成相应的UI和对应的事件
     */
    @SuppressLint("SetTextI18n")
    private fun setupEqualizeFxAndUi() {
        mEqualizer = Equalizer(0, mMediaPlayer!!.getAudioSessionId())
        mEqualizer.setEnabled(true)// 启用均衡器
        val eqTextView = TextView(this)
        eqTextView.text = "均衡器："
        mLayout.addView(eqTextView)

        // 通过均衡器得到其支持的频谱引擎
        val bands = mEqualizer.getNumberOfBands()

        // getBandLevelRange 是一个数组，返回一组频谱等级数组，
        // 第一个下标为最低的限度范围
        // 第二个下标为最大的上限,依次取出
        val minEqualizer = mEqualizer.getBandLevelRange()[0]
        val maxEqualizer = mEqualizer.getBandLevelRange()[1]

        for (i in 0 until bands) {

            val freqTextView = TextView(this)
            freqTextView.layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )

            freqTextView.gravity = Gravity.CENTER_HORIZONTAL

            // 取出中心频率
            freqTextView.text = (mEqualizer.getCenterFreq(i.toShort()) / 1000).toString() + "HZ"
            mLayout.addView(freqTextView)

            val row = LinearLayout(this)
            row.orientation = LinearLayout.HORIZONTAL

            val minDbTextView = TextView(this)
            minDbTextView.layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )

            minDbTextView.text = (minEqualizer / 100).toString() + " dB"

            val maxDbTextView = TextView(this)
            maxDbTextView.layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            maxDbTextView.text = (maxEqualizer / 100).toString() + " dB"

            val layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )

            layoutParams.weight = 1f

            val seekbar = SeekBar(this)
            seekbar.layoutParams = layoutParams
            seekbar.max = maxEqualizer - minEqualizer
            seekbar.setProgress(mEqualizer.getBandLevel(i.toShort()).toInt())

            seekbar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {

                override fun onStopTrackingTouch(seekBar: SeekBar) {}

                override fun onStartTrackingTouch(seekBar: SeekBar) {}

                override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    mEqualizer.setBandLevel(i.toShort(), (progress + minEqualizer).toShort())
                }
            })
            row.addView(minDbTextView)
            row.addView(seekbar)
            row.addView(maxDbTextView)

            mLayout.addView(row)
        }

    }

    /**
     * 生成一个VisualizerView对象，使音频频谱的波段能够反映到 VisualizerView上
     */
    private fun setupVisualizerFxAndUi() {
        mVisualizerView = VisualizerView(this)
        mVisualizerView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            (VISUALIZER_HEIGHT_DIP * resources.displayMetrics.density).toInt()
        )
        mLayout.addView(mVisualizerView)

        mVisualizer = Visualizer(mMediaPlayer!!.getAudioSessionId())
        // 参数内必须是2的位数
        mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1])

        // 设置允许波形表示，并且捕获它
        mVisualizer.setDataCaptureListener(object : OnDataCaptureListener {

            override fun onWaveFormDataCapture(visualizer: Visualizer, waveform: ByteArray, samplingRate: Int) {
                mVisualizerView.updateVisualizer(waveform)
            }

            override fun onFftDataCapture(visualizer: Visualizer, fft: ByteArray, samplingRate: Int) {

            }
        }, Visualizer.getMaxCaptureRate() / 2, true, false)

    }

    override fun onPause() {
        // TODO Auto-generated method stub
        super.onPause()
        if (isFinishing && mMediaPlayer != null) {
            mVisualizer.release()
            mMediaPlayer!!.release()
            mEqualizer.release()
            mMediaPlayer = null
        }
    }
}